package org.hitchhike.core.aspect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class SystemLogAspect {
  private Logger logger = LoggerFactory.getLogger(getClass());

  ThreadLocal<Long> startTime = new ThreadLocal<>();

  @Pointcut("execution(public * org.hitchhike.web..*.*(..))")
  public void systemControllerLog() {}

  @Before("systemControllerLog()")
  public void doBefore(JoinPoint joinPoint) {
    HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    HttpSession session = request.getSession();
    String ip = request.getRemoteAddr();

    try {
      logger.info("====================");
      logger.info("请求方法:" + (joinPoint.getTarget().getClass().getName() + "."
          + joinPoint.getSignature().getName() + "()"));

      logger.info("请求IP:" + ip);

      for (int i = 0; i < joinPoint.getArgs().length; i++) {
        logger.info("请求参数:" + joinPoint.getArgs()[i]);
      }

      logger.info("====================");
    } catch (Exception e) {
      logger.error("====================");
      logger.error("异常信息:{}", e.getMessage());
    }
  }

}
